package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.bean.AddCarBean;
import com.rh.bmw4s.bean.RecyUsedCarBean;
import com.rh.bmw4s.bean.UpLoadImgBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.inter.AddressPickTask;
import com.rh.bmw4s.utills.CheckUtil;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.KeyboardUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.utills.glide.GlideImageLoader;
import com.rh.bmw4s.view.PicassoImageLoader;
import com.rh.bmw4s.view.fragdialog.SelectColorDialog;
import com.rh.bmw4s.view.fragdialog.SelectStateDialog;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.DatePicker;

/**
 * 回收二手车界面
 */
public class RecyUsedCarActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.tv_select_xinghao)
    TextView tvXinghao;
    @BindView(R.id.img_recycar_photo)
    ImageView imgPhoto;
    @BindView(R.id.rel_recycar_selectimg)
    RelativeLayout relSelectimg;
    @BindView(R.id.tv_select_city)
    TextView tvCity;
    @BindView(R.id.tv_select_shangpaidate)
    TextView tvShangpaidate;
    @BindView(R.id.edit_recycar_licheng)
    EditText editLicheng;
    @BindView(R.id.tv_select_carcolor)
    TextView tvCarcolor;
    @BindView(R.id.tv_select_guohu)
    TextView tvGuohu;
    @BindView(R.id.tv_select_state)
    TextView tvState;
    @BindView(R.id.tv_select_neishi)
    TextView tvNeishi;
    @BindView(R.id.tv_select_waiguan)
    TextView tvWaiguan;
    @BindView(R.id.edit_recycar_name)
    EditText editName;
    @BindView(R.id.edit_recycar_phone)
    EditText editPhone;
    @BindView(R.id.btn_recycar_commit)
    TextView btnCommit;
    @BindView(R.id.edit_recycar_detailaddress)
    EditText editDetailaddress;

    private GlideImageLoader imageLoader;
    private Gson gson = null;
    private static final int IMAGE_PICKER = 202;
    private String imgPath = "";    //上传图片后，返回的地址
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recy_used_car);
        ButterKnife.bind(this);
        initView();
        initPicker();
    }

    private void initView() {
        KeyboardUtils.hideSoftInput(RecyUsedCarActivity.this);
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("回收二手车");
        imageLoader = new GlideImageLoader(RecyUsedCarActivity.this);
        gson = new Gson();
        userId = SPUtils.getInstance().getInt(ConfigValue.userId);
        editDetailaddress.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    editDetailaddress.setCursorVisible(true);
                }
                return false;
            }
        });
    }

    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(false);  //单选
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_select_xinghao, R.id.rel_recycar_selectimg,
            R.id.tv_select_city, R.id.tv_select_shangpaidate, R.id.tv_select_carcolor,
            R.id.tv_select_guohu, R.id.tv_select_state, R.id.tv_select_neishi, R.id.tv_select_waiguan,
            R.id.btn_recycar_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.tv_select_xinghao:                   //车辆型号
                Intent intent = new Intent(RecyUsedCarActivity.this, SelectCarTypeActivity.class);
                startActivityForResult(intent, 134);
                break;
            case R.id.rel_recycar_selectimg:               //选择图片
                Intent intent1 = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent1, IMAGE_PICKER);
                break;
            case R.id.tv_select_city:
                chooseCity();
                break;
            case R.id.tv_select_shangpaidate:
                chooseDateShangPai();
                break;
            case R.id.tv_select_carcolor:
                showSelect(1);
                break;
            case R.id.tv_select_guohu:
                showSelect(2);
                break;
            case R.id.tv_select_state:
                showCarState(1);
                break;
            case R.id.tv_select_neishi:
                showCarState(2);
                break;
            case R.id.tv_select_waiguan:
                showCarState(3);
                break;
            case R.id.btn_recycar_commit:
                if (checkInfo()) {
                    beginCommit();
                }
                break;
        }
    }

    private void showCarState(final int type) {
        final SelectStateDialog stateDialog = new SelectStateDialog();
        stateDialog.setType(type);
        stateDialog.show(getFragmentManager(), "stateDialog");
        stateDialog.setStateItemClickListener(new SelectStateDialog.OnStateItemClickListener() {
            @Override
            public void stateItemSelect(String strState) {
                switch (type) {
                    case 1:
                        tvState.setText(strState);
                        break;
                    case 2:
                        tvNeishi.setText(strState);
                        break;
                    case 3:
                        tvWaiguan.setText(strState);
                        break;
                }
                stateDialog.dismiss();
            }
        });
    }

    private void showSelect(final int i) {
        final SelectColorDialog selectColorDialog = new SelectColorDialog();
        selectColorDialog.setType(i);
        selectColorDialog.show(getFragmentManager(), "selectColorDialog");
        selectColorDialog.setSelectItemClickListener(new SelectColorDialog.OnSelectItemClickListener() {
            @Override
            public void pullSelect(String s) {
                if (i == 1) {
                    tvCarcolor.setText(s);
                } else {
                    tvGuohu.setText(s);
                }
                selectColorDialog.dismiss();
            }
        });
    }

    /**
     * 选择城市
     */
    private void chooseCity() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                ToastUtils.toastForShort(RecyUsedCarActivity.this, "地址数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                if (county == null) {
                    tvCity.setText(province.getAreaName() + city.getAreaName());
                    //  ToastUtils.toastForShort(RecyUsedCarActivity.this, province.getAreaName() + city.getAreaName());
                } else {
                    tvCity.setText(province.getAreaName() + city.getAreaName() + county.getAreaName());
                    //  ToastUtils.toastForShort(RecyUsedCarActivity.this, province.getAreaName() + city.getAreaName() + county.getAreaName());
                }
            }
        });
        task.execute("河南", "郑州", "金水");
    }

    /**
     * 选择上牌日期
     */
    private void chooseDateShangPai() {
        final DatePicker picker = new DatePicker(this);
        picker.setCanceledOnTouchOutside(false);
        //设置滚轮项填充宽度，分割线最长
        picker.setUseWeight(true);
        picker.setRangeEnd(2017, 10, 16);
        picker.setRangeStart(1980, 1, 1);
        picker.setSelectedItem(2010, 1, 1);
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tvShangpaidate.setText(year + "-" + month + "-" + day);
            }
        });
        picker.show();
    }


    private String strName = "";
    private String strPhone = "";

    private String strXinghao = "";
    private String strCity = "";
    private String strDetailAddress = "";
    private String strShangPaiDate = "";
    private String strLiCheng = "";
    private String strColor = "";
    private String strGuoHu = "";
    private String strState = "";
    private String strNeishi = "";
    private String strWaiGuan = "";

    private String strThing = "";
    private String strInterior = "";
    private String strAppearance = "";

    /**
     * 开始提交
     */
    private void beginCommit() {
        DialogUtils.showProgressDlg(RecyUsedCarActivity.this, "正在提交......");


        if (TextUtils.equals("优", strState)) {
            strThing = "优:" + getResources().getString(R.string.gongkuang_nice);
        } else if (TextUtils.equals("良", strState)) {
            strThing = "良:" + getResources().getString(R.string.gongkuang_good);
        } else if (TextUtils.equals("中", strState)) {
            strThing = "中:" + getResources().getString(R.string.gongkuang_middle);
        } else {
            strThing = "差:" + getResources().getString(R.string.gongkuang_bad);
        }

        if (TextUtils.equals("优", strNeishi)) {
            strInterior = "优:" + getResources().getString(R.string.neishi_nice);
        } else if (TextUtils.equals("良", strNeishi)) {
            strInterior = "良:" + getResources().getString(R.string.neishi_good);
        } else if (TextUtils.equals("中", strNeishi)) {
            strInterior = "中:" + getResources().getString(R.string.neishi_middle);
        } else {
            strInterior = "差:" + getResources().getString(R.string.neishi_bad);
        }

        if (TextUtils.equals("优", strWaiGuan)) {
            strAppearance = "优:" + getResources().getString(R.string.waiguan_nice);
        } else if (TextUtils.equals("良", strWaiGuan)) {
            strAppearance = "良:" + getResources().getString(R.string.waiguan_good);
        } else if (TextUtils.equals("中", strWaiGuan)) {
            strAppearance = "中:" + getResources().getString(R.string.waiguan_middle);
        } else {
            strAppearance = "差:" + getResources().getString(R.string.waiguan_bad);
        }

//        LogUtils.d("mmm", strThing);
//        LogUtils.d("mmm", strInterior);
//        LogUtils.d("mmm", strAppearance);
        OkGo.<String>post(Constant.UploadUsedCar)
                .tag(RecyUsedCarActivity.this)
                .params("member_id", userId)
                .params("xinghao", strSelectCarId)
                .params("thumb", imgPath)
                .params("city", strCity + strDetailAddress)
                .params("firsttime", strShangPaiDate)
                .params("mile", Integer.parseInt(strLiCheng))
                .params("colors", strColor)
                .params("change_time", strGuoHu)
                .params("thing", strThing)
                .params("interior", strInterior)
                .params("appearance", strAppearance)
                .params("name", strName)
                .params("mobile", strPhone)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("mmm", response.body().toString());
                        RecyUsedCarBean bean = gson.fromJson(response.body().toString(), RecyUsedCarBean.class);
                        ToastUtils.toastForShort(RecyUsedCarActivity.this, bean.getMsg());
                        if (bean.getStatus() == Constant.SUCESS) {
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(RecyUsedCarActivity.this, "提交失败，请重试");
                    }
                });


    }

    /**
     * 检查必填项是否填写
     */
    private boolean checkInfo() {
        strXinghao = tvXinghao.getText().toString();             //型号
        strCity = tvCity.getText().toString();               //城市
        strDetailAddress = editDetailaddress.getText().toString(); //详细地址
        strShangPaiDate = tvShangpaidate.getText().toString();     //上牌日期
        strLiCheng = editLicheng.getText().toString();        //行驶里程
        strColor = tvCarcolor.getText().toString();          //颜色
        strGuoHu = tvGuohu.getText().toString();          //过户次数
        strState = tvState.getText().toString();           //工况
        strNeishi = tvNeishi.getText().toString();             //内饰
        strWaiGuan = tvWaiguan.getText().toString();            //外观
        strName = editName.getText().toString();             //联系人姓名
        strPhone = editPhone.getText().toString();            //电话

        if (TextUtils.isEmpty(strXinghao)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "车辆型号不能为空");
            return false;
        }
        if (TextUtils.isEmpty(imgPath)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "图片不能为空");
            return false;
        }

        if (TextUtils.isEmpty(strCity)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "城市不能为空");
            return false;
        }

        if (TextUtils.isEmpty(strDetailAddress)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "详细地址不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strShangPaiDate)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "上牌日期不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strLiCheng)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "行驶里程不能为空");
            return false;
        }

        if (TextUtils.isEmpty(strColor)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "汽车颜色不能为空");
            return false;
        }

        if (TextUtils.isEmpty(strGuoHu)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "过户次数不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strState)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "车况不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strNeishi)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "车辆内饰不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strWaiGuan)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "外观状况不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strName)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "联系人姓名不能为空");
            return false;
        }

        if (!CheckUtil.isMobileNO(strPhone)) {
            ToastUtils.toastForShort(RecyUsedCarActivity.this, "手机号码错误");
            return false;
        }
        return true;
    }


    private int strSelectCarId;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择车辆型号
        if (requestCode == 134 && resultCode == 135) {
            strSelectCarId = data.getExtras().getInt("selectCarId");
            String strSelectCarname = data.getExtras().getString("selectCarName");
            tvXinghao.setText(strSelectCarname);
        }
        //选择车辆图片
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem item = images.get(0);
                upLoadImg(item.path);
                // imageLoader.displayCircle(item.path, imgPhoto);
            } else {
                ToastUtils.toastForShort(RecyUsedCarActivity.this, "图片未获取");
            }
        }

    }

    private void upLoadImg(final String selectPath) {
        DialogUtils.showProgressDlg(RecyUsedCarActivity.this, "正在上传....");
        OkGo.<String>post(Constant.UpLoadImg)
                .tag(RecyUsedCarActivity.this)
                .params("logo", new File(selectPath))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("fff", selectPath);
                        LogUtils.d("fff", response.body().toString());
                        UpLoadImgBean imgBean = gson.fromJson(response.body().toString(), UpLoadImgBean.class);
                        if (imgBean.getStatus() == Constant.SUCESS) {
                            imageLoader.displayCircle(selectPath, imgPhoto);
                            imgPath = imgBean.getDatas();
                        } else {

                            ToastUtils.toastForShort(RecyUsedCarActivity.this, "上传失败");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(RecyUsedCarActivity.this, "上传失败");

                    }
                });
    }


}
